package com.lanou.controller;

import com.lanou.bean.AdminInfo;
import com.lanou.bean.ModuleInfo;
import com.lanou.bean.RoleGuanLiBean;
import com.lanou.service.AdminInfoService;
import com.lanou.service.ModuleInfoService;
import com.lanou.service.RoleInfoService;
import com.lanou.utils.AjaxResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by dllo on 18/3/8.
 */
@Controller
public class MainController {

    @Resource
    private RoleInfoService roleInfoService;
    @Resource
    private ModuleInfoService moduleInfoService;

    @RequestMapping(value = {"/","/index"})
    public String index(){
        return "index";
    }
    @RequestMapping(value = "/login")
    public String login () {
        if (SecurityUtils.getSubject().isAuthenticated()){
            return "redirect:index";
        }
        return "login";
    }
    @RequestMapping(value = "/error")
    public String error(){
        return "error";
    }


    @RequestMapping(value = "/loginsubmit")
    public AjaxResult loginsubmit(HttpServletRequest request) throws Exception {
        //因为表单过滤器的原因,这个方法不需要接受用户名密码,再进行login
        //而是由过滤器直接把用户名密码交给realm来做认证

        //我们在这个方法中,就只处理异常就可以了

        //过滤器先于Servlet执行,所以当在realm中处理认证时出现异常
        //过滤器会把异常信息保存到request中发给Servlet,即交给我们来处理
        //1.获取异常的名字
        String exName = (String) request.getAttribute("shiroLoginFailure");
        if (UnknownAccountException.class.getName().equals(exName)) {
            throw new UnknownAccountException("账号不存在");
        } else if (IncorrectCredentialsException.class.getName().equals(exName)) {
            throw new IncorrectCredentialsException("密码错误");
        } else {
            throw new Exception("我也不知到为啥不对");
        }
    }

    /**
     * 查询当前用户所拥有的所有的权限
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/selectAllModules")
    public List<String> selectAllModules(){
        Subject subject = SecurityUtils.getSubject();
        AdminInfo adminInfo = (AdminInfo) subject.getPrincipal();
        String name = adminInfo.getName();
        List<ModuleInfo> moduleInfoList = moduleInfoService.selectModule(name);
        List<String> list = new ArrayList<>();
        for (ModuleInfo moduleInfo : moduleInfoList){
            list.add(moduleInfo.getName());
        }
        return list;
    }




}
